<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>打字游戏</h2>
    <h3>分数：0</h3>
    <h4>血量：10</h4>

    <div
      style="
        width: 400px;
        height: 200px;
        background: pink;
        font-size: 60px;
        text-align: center;
      "
    >
      <button style="width: 100px; height: 50px; background: peru">开始</button>
    </div>
  </body>
  <script>
    function randomnum(min, max) {
      return parseInt(Math.random() * (max - min) + min);
    }
    var arr = [
      "html",
      "head",
      "body",
      "meta",
      "char",
      "set",
      "title",
      "document",
      "width",
      "height",
      "float",
      "none",
      "tab",
      "background",
      "color",
      "position",
      "repeat",
      "type",
      "left",
      "alt",
      "right",
      "top",
      "bottom",
      "center",
      "font",
      "size",
      "weight",
      "style",
      "type",
      "family",
      "line",
      "text",
      "underline",
      "none",
      "position",
      "repeat",
      "image",
      "input",
      "button",
      "reset",
      "submit",
      "file",
      "radio",
      "checkbox",
      "nav",
    ];
    var score = 0;
    var falseInput = 10;
    var btn = document.querySelector("button");
    var divEle = document.querySelector("div");
    function changeTospan(ele) {
      //1.函数功能：给调用的元素节点出现随机单词+每个字符加一个span
      ele.innerHTML = "";
      var str = `${arr[randomnum(0, arr.length)]}`;
      var newStr = "";
      for (var i = 0; i < str.length; i++) {
        newStr += `<span>${str[i]}</span>`;
      }
      ele.innerHTML = newStr;
    }
    btn.onclick = function () {
      var res = confirm("输错十次结束游戏");
      if (res) {
        btn.style.display = "none";
        //给页面初始化一个单词
        changeTospan(divEle);
        document.onkeydown = function (e) {
          var e = e || window.e;
          //单词判断  按键变色 错误退出
          if (falseInput > 0) {
            if (key) {
              m++;
              e++;
            }
            if (w) {
              score += 1;
              var scoreEle = document.querySelector("h3");
              scoreEle.innerHTML = `分数:${score}`;
              changeTospan(divEle);
            } else {
              falseInput--;
              var blood = document.querySelector("h4");
              blood.innerHTML = `血量：${falseInput}`;
              changeTospan(divEle);
            }
          } else {
            divEle.innerHTML = "game over";
          }
        };
      }
    };
  </script>
</html>
